package com.agileai.crm.module.taskcycle.handler;

import java.util.Date;

import com.agileai.crm.cxmodule.TaskCycleManage;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.controller.core.StandardEditHandler;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.RedirectRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.DateUtil;

public class TaskCycleManageEditHandler
        extends StandardEditHandler {
    public TaskCycleManageEditHandler() {
        super();
        this.listHandlerClass = TaskCycleManageListHandler.class;
        this.serviceId = buildServiceId(TaskCycleManage.class);
    }
    
	public ViewRenderer prepareDisplay(DataParam param) {
		String operaType = param.get(OperaType.KEY);
		if (isReqRecordOperaType(operaType)){
			DataRow record = getService().getRecord(param);
			this.setAttributes(record);	
		}else{
			Date date = DateUtil.getBeginOfWeek(new Date());
			String dateBeginStr = DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL, date);
			String dateEndStr = DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL, DateUtil.getDateAdd(date, DateUtil.DAY, 6));
			this.setAttribute("TC_BEGIN", dateBeginStr);
			this.setAttribute("TC_END", dateEndStr);
		}
		
		this.setOperaType(operaType);
		processPageAttributes(param);
		return new LocalRenderer(getPage());
	}
	
	public ViewRenderer doSaveAction(DataParam param){
		String operateType = param.get(OperaType.KEY);
		Date tcBegin = DateUtil.getDateTime(param.get("TC_BEGIN"));
		Date tcEnd = DateUtil.getDateTime(param.get("TC_END"));
		if(tcBegin.after(tcEnd)){
			this.setErrorMsg("开始日期不能大于结束日期");
			return prepareDisplay(param);
		}
		if (OperaType.CREATE.equals(operateType)){
			getService().createRecord(param);	
		}
		else if (OperaType.UPDATE.equals(operateType)){
			getService().updateRecord(param);	
		}
		
		if (this.redirectListAfterSave){
			return new RedirectRenderer(getHandlerURL(listHandlerClass));	
		}else{
			param.put(OperaType.KEY,OperaType.UPDATE);
			return prepareDisplay(param);
		}
	}

    protected void processPageAttributes(DataParam param) {
    }

    protected TaskCycleManage getService() {
        return (TaskCycleManage) this.lookupService(this.getServiceId());
    }
}
